/**
 * Project Name:JZGPingGuShi
 * File Name:AppManager.java
 * Package Name:com.gc.jzgpinggushi.app
 * Date:2014-9-1上午10:18:48
 * Copyright (c) 2014, wangyd523@gmail.com All Rights Reserved.
 */

package com.qiwx.pigeon.app;

import android.app.Activity;


import com.qiwx.pigeon.Utils.LogUtil;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

/**
 */
public class AppManager {
    private static final String TAG = AppManager.class.getSimpleName();
    private static Stack<Activity> activityStack;

    private static AppManager instance;

    private AppManager() {
    }

    public static AppManager getAppManager() {
        if (instance == null) {
            instance = new AppManager();
        }
        return instance;
    }

    public void addActivity(Activity activity) {
        if (activityStack == null) {
            activityStack = new Stack<Activity>();
        }
        activityStack.add(activity);
    }
    public Activity getTopActivity() {
        Activity topActivity = null;
        if (activityStack != null && activityStack.size()>0) {
            //TODO 有可能爲空
            topActivity = activityStack.pop();
            LogUtil.e(TAG,"TopActivity:"+topActivity.getClass().getCanonicalName());
            return topActivity;
        }
        return null;
    }

    public Activity currentActivity() {
        if(activityStack!=null&&activityStack.size()>0){
            Activity activity = activityStack.lastElement();
            return activity;
        }
       return null;
    }

    public void finishActivity() {
        Activity activity = activityStack.lastElement();
        finishActivity(activity);
    }

    public synchronized void finishActivity(Activity activity) {
        if (activity != null) {
            activityStack.remove(activity);
            activity.finish();
            activity = null;
        }
    }

    public void finishActivity(Class<?> cls) {
        List<Activity> targetActivityList = new ArrayList<>();
        for (Activity activity : activityStack) {
            if (activity.getClass().equals(cls)) {
                targetActivityList.add(activity);
                activity.finish();
            }
        }
        if (!targetActivityList.isEmpty())
            activityStack.removeAll(targetActivityList);
    }

    public boolean isInActivityStack(Class<?> cls) {
        for (Activity activity : activityStack) {
            if (activity.getClass().equals(cls)) {
                return true;
            }
        }
        return false;
    }

    public void finishAllActivity() {
        for (int i = 0, size = activityStack.size(); i < size; i++) {
            if (null != activityStack.get(i)) {
                activityStack.get(i).finish();
            }
        }
        activityStack.clear();
    }
}
